package com.hotec.PROJECT_NAME.component.basic;

import cn.hutool.core.util.ObjectUtil;
import com.google.common.collect.Lists;
import com.hotec.PROJECT_NAME.config.encrypt.MyHandlerMethodReturnValueHandler;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor;

import java.util.List;

@Component
public class ApplicationInit implements ApplicationListener<ContextRefreshedEvent> {
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        ApplicationContext applicationContext = contextRefreshedEvent.getApplicationContext();

        //加密处理
        handleEncryptAdapter(applicationContext);
    }

    private void handleEncryptAdapter(ApplicationContext applicationContext) {
        RequestMappingHandlerAdapter mappingHandlerAdapter = applicationContext.getBean(RequestMappingHandlerAdapter.class);

        List<HandlerMethodReturnValueHandler> returnValueHandlers = mappingHandlerAdapter.getReturnValueHandlers();

        if(ObjectUtil.isNotNull(returnValueHandlers)){
            List<HandlerMethodReturnValueHandler> handlers = Lists.newArrayList(returnValueHandlers);

            for (int i = 0; i < handlers.size(); i++) {
                HandlerMethodReturnValueHandler handler = handlers.get(i);

                if(handler instanceof RequestResponseBodyMethodProcessor){
                    MyHandlerMethodReturnValueHandler decorator = new MyHandlerMethodReturnValueHandler(
                            (RequestResponseBodyMethodProcessor) handler);

                    handlers.set(i, decorator);

                    break;
                }
            }

            mappingHandlerAdapter.setReturnValueHandlers(handlers);
        }
    }
}
